﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using GameView.Comment;
using GameView.Services;
using GameView.Services.Comment;
using GameView.Services.Dtos.Persons;
using GameView.Services.Dtos.Project;
using GameView.Services.Dtos.RechargesDto;
using MaterialDesignThemes.Wpf;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;

namespace GameView.ViewModels
{
    public partial class RechargeAddToMeViewModel : ObservableValidator
    {
        private List<ProjectWithGamesInfo> _projectWithGamesInfos;
        private readonly RechargeToMService _service;
        private readonly UserService _userService;
        private readonly IMessenger _messenger;

        public RechargeAddToMeViewModel(RechargeToMService service, UserService userService)
        {
            _service = service;
            _userService = userService;
            LoadPG().ConfigureAwait(false);
        }

        [ObservableProperty]
        private bool _isDialog = true;

        [ObservableProperty]
        private ObservableCollection<TreeNode> _nodes = [];

        private List<PersonnelSimple> allPerson = [];

        [ObservableProperty]
        private bool _isIncreaseSelected = true; // 默认选中"增加"

        [ObservableProperty]
        private bool _isDecreaseSelected = false;

        [ObservableProperty]
        [NotifyDataErrorInfo]
        [Required(ErrorMessage = "请选择商人")]
        private TreeNode? _selectedPerson;

        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        private string _nowPersonName = "";

        [ObservableProperty]
        private string _searchStr = "";

        [ObservableProperty]
        [NotifyDataErrorInfo]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        [Range(1, 999999999, ErrorMessage = "充值金额必须在1-999999999之间")]
        private uint? _rechargeAmount = null;

        [ObservableProperty]
        private string _rechargeAmountStr = string.Empty;

        [ObservableProperty]
        private string remark = string.Empty;

         partial void OnRechargeAmountStrChanged(string value)
        {
            if (uint.TryParse(value, out var res))
                RechargeAmount = res;
            else
                RechargeAmount = 0;
        }

         partial void OnSearchStrChanged(string value)
        {
            // 属性变更时自动执行搜索
            Search();
        }

        private async Task<bool> LoadPG()
        {
            var allUser = await _userService.GetAllByRoleAsync();
            if (allUser.Data.IsNullOrEmpty())
            {
                return false;
            }
            allPerson = allUser.Data.FindAll(q => q.RoleId == 3);

            Nodes.Clear();
            var psp = allPerson.GroupBy(q => q.ProjectName);
            foreach (var p in psp)
            {
                var pN = new TreeNode() { IsParent = true, Name = p.Key };
                foreach (var n in p.ToList())
                {
                    var ppN = new TreeNode() { Parent = pN, IsParent = false, Name = n.Account };

                    pN.Children.Add(ppN);
                }
                Nodes.Add(pN);
            }

            return true;
        }

        [RelayCommand]
        private void SelectedItemChanged(TreeNode value)
        {
            if (value != null && value.Parent != null)
            {
                SelectedPerson = value;
                IsIncreaseSelected = true;
                IsDecreaseSelected = false;
                RechargeAmount = 0;
                NowPersonName = value.Parent.Name + "/" + value.Name;
            }
        }

        [RelayCommand]
        private void Search()
        {
            //Nodes.Clear();
            //List<PersonnelSimple> p = [];
            //if (SearchStr.IsNullOrEmpty())
            //    p = allPerson;
            //else
            //    p = allPerson.FindAll(q => q.Account.Contains(SearchStr) || q.Name.Contains(SearchStr));
            //foreach (var pi in p)
            //{
            //    Nodes.Add(pi);
            //}
        }

        [RelayCommand(CanExecute = nameof(CanSubmit))]
        private async Task Submit()
        {
            var dto = new RechargeToMAddDto
            {
                ProjectName = SelectedPerson.Parent.Name,
                MerchantName = SelectedPerson.Name,
                Remark = Remark,
                ChangeType = IsDecreaseSelected ? 4002 : 4001,
                RechargeAmount = (int)RechargeAmount,
            };

            var res = await _service.AddNewAsync(dto);
            if (res.StatusCode == 200)
            {
                // 关闭弹窗
                if (IsDialog)
                    DialogHost.CloseDialogCommand.Execute(null, null);
                else
                {
                    RechargeAmount = 0;
                }
                //GlobalMessage.Instance.ShowSuccess("操作成功！");
            }
            else
            {
                GlobalMessage.Instance.ShowError($"操作失败：{res.Errors}");
            }
        }

        private bool CanSubmit() => !HasErrors && SelectedPerson != null && RechargeAmount >= 1;
    }
}